/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package exemple;


import java.util.List;
 
 
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

 
import util.HibernateUtil;
 
public class HistoricSystemDAO extends HibernateUtil {
 
    public HistoricSystem add(HistoricSystem historicSystem) {
        System.out.println(historicSystem);
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        session.saveOrUpdate(historicSystem);
        session.getTransaction().commit();
        return historicSystem;
    }  
    
    public List<HistoricSystem> listHistroic(int id_address) {
         
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List<HistoricSystem> listHistoric = null;
        try {
             
            //listHistoric = (List<HistoricSystem>)session.createQuery("from HistoricSystem").list();
            Query query = session.createQuery("from HistoricSystem where id_address in (:id_address) order by id_historic desc");
            query.setParameter("id_address", id_address);
            
            listHistoric = (List<HistoricSystem>)query.list();
             
        } catch (HibernateException e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
        session.getTransaction().commit();
        return listHistoric;
    }

    public HistoricSystem getHisto(int id_historic) {
        HistoricSystem hi = null;
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        try {
            hi = (HistoricSystem) session.get(HistoricSystem.class, id_historic);
            System.out.println(hi);
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
        }
        session.getTransaction().commit();
        return hi;
    }

    public void supp_histo(int id_address) {
 
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Query q = session.createQuery("from HistoricSystem where id_address = :id_address ");

        q.setParameter("id_address", id_address);

        HistoricSystem hi = (HistoricSystem)q.list().get(0);

        for (ProcessusB p : hi.getListProcess()){
                 session.delete(p);
        }
        session.delete(hi);

        session.getTransaction().commit();
    }
}